package dk.au.cs.peterbn.processing;

import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Options;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * A wrapper for the compiler options, that encapsulates lookup.
 * @author pebn.
 */
public class CompilerOptions {

    private Options options;

    public CompilerOptions(JavacProcessingEnvironment env) {

        if (env != null) {
            Context context = env.getContext();
            options = Options.instance(context);
        }
    }

    /**
     * Get the urls where the reflections framework should look for classes
     * @return URLS for the instantiation of the reflections framework
     */
    public Set<URL> getPatternLookupUrls() {
        Set<URL> urls = new HashSet<URL>();
        String classpath = getClassPath();
        if (classpath != null && classpath.length() > 0) {
            String[] classpathArray = classpath.split(File.pathSeparator);
            for (String s : classpathArray) {
                addUrl(urls, s);
            }
        }
        String outputDir = getOutputDir();
        if (outputDir != null && outputDir.length() > 0) {
            addUrl(urls, outputDir);
        }

        return urls;

    }

    protected String getOutputDir() {
        return options != null ? options.get("-d") : null;
    }

    protected String getClassPath() {
        String classpath = options != null ? options.get("-classpath") : null;
        if (classpath == null || classpath.length() == 0) {
            classpath = options != null ? options.get("-cp") : null;
        }
        if (classpath != null) {
            List<String> paths = new LinkedList<String>(Arrays.asList(classpath.split(File.pathSeparator)));
            Iterator<String> iterator = paths.iterator();
//            while (iterator.hasNext()) {
//                String next = iterator.next();
//                if (next.endsWith(".jar")) {
//                    iterator.remove();
//                }
//            }
            classpath = join(paths, File.pathSeparator);

        }
        return classpath;
    }

    private static String join(Iterable<String> strings, String separator) {
        Iterator<String> it = strings.iterator();
        if (it.hasNext()) {
            StringBuilder sb = new StringBuilder(it.next());
            while (it.hasNext()) {
                sb.append(separator).append(it.next());
            }
            return sb.toString();
        } else {
            return "";
        }
    }

    private void addUrl(Set<? super URL> urls, String s) {
        File file = new File(s);

        try {
            URL url = file.getAbsoluteFile().toURI().toURL();
            urls.add(url);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Things really gone wrong here", e);
        }
    }
}
